%pip install pypdf spacytextblobNatural Language Processing
Workshop 4 
Background
Exxon Mobil is the 4th largest oil company in the world. In 1978, an Exxon scientist named James Black wrote an internal briefing called “The Greenhouse Effect” in which he warned: “Present thinking holds that man has a time window of five to ten years before the need for hard decisions regarding changes in energy strategies might become critical.”
Rather than acting on this information, Exxon spent the next forty years aggressively funding climate denial. Recently, a U.S. court ruled that ExxonMobil must face trial over accusations that it lied about the climate crisis and covered up the fossil fuel industry’s role in worsening environmental devastation.
Earnings Calls
Every three months, Exxon conducts an “earnings call”; a conference call between the management of a public company, analysts, investors, and the media to discuss the company’s financial results during a given reporting period, such as a quarter or a fiscal year.
You can register to attend their next one if you want! No worries if you miss it, they provide transcripts on their website.
These transcripts provide an intimate window into the company’s dealings. We can see how much pressure investors are putting on the company to tackle climate change, and how the company responds.
We’ll be working with transcripts spanning nearly 20 years and almost 2 million words; that’s like reading the Harry Potter series twice. Then, we’ll look at a sample of 100,000 tweets that use the #ExxonKnew hashtag, and analyze public pressure on the company.

Setup
Install the packages we need (this takes a minute), import them, and load spaCy’s English model.
import io
import re
import requests
import spacy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pypdf import PdfReader
from spacytextblob.spacytextblob import SpacyTextBlob
plt.rcParams['figure.figsize'] = (10., 8.)
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe('spacytextblob')From a PDF to a table
Exxon publishes its quarterly results on its website as PDFs. PDFs are made for printing, not for analysis, but the python package pypdf can pull the text out of one. Let’s download Exxon’s results for the second quarter of 2023 and read it:
# the URL where the PDF lives
url = 'https://d1io3yog0oux5.cloudfront.net/_74d009918ead0ec6acdd6bbaf27a8316/exxonmobil/db/2288/22123/earnings_release/XOM+2Q23+Earnings+Press+Release+Website.pdf'
# download the file, and open it with pypdf
pdf = PdfReader(io.BytesIO(requests.get(url).content))
# extract the text of every page and join the pages together
raw_text = '\n'.join(page.extract_text() for page in pdf.pages)Now we have the text in a string called raw_text. The PDF also carries some metadata, such as the date it was created, in pdf.metadata. The title is the first line of the text:
date = pdf.metadata.creation_date
title = raw_text.split('\n')[0]
print('Date: ', date)
print('Title: ', title)
print('Word Count: ', len(raw_text.split()))
print('Text:')
raw_text[:1000]look at that! we’re beginning to give some structure to our text data. But suppose I wanted to analyze multiple earnings calls; I need to organize this data so that it can accomodate new entries. As always, we want to tabularize our data. Let’s create a dataframe with three columns (Date, Title, and Text) in which each row is one earnings call:
# create a dataframe using the above data
call=pd.DataFrame({'Date':[date],'Title':[title],'Text':[raw_text]})
# remember, datetime information almost always reaches us as text.
# we need to explicitly convert it to the datetime data type.
call['Date']=pd.to_datetime(call['Date'])
# Let's see what we've got.
callNow, if we were so inclined, we could use a loop to repeat this process for a large number of earnings calls, yielding a neatly organized dataframe containing the date, title, and text of earnings calls over time. I’ve done this so you don’t have to, and stored it as a file called “Exxon.json”. It spans 2002-2019, and contains almost 2 million words’ worth of earnings calls. Let’s take a peek:
df=pd.read_json('https://storage.googleapis.com/qm2/wk4/Exxon.json')
dfDirty Words
Text is rarely clean. You may have noticed \n scattered through the text above: it’s a character (just like “a” or “$”) that means “start a new line”, left over from the PDF’s layout. Be warned that cleaning text can take up a lot of a text analysis project. Our transcripts are already fairly tidy, so let’s pick one, the 38th in the dataframe:
call=df.iloc[38]
print('Date: ', call['Date'])
print('Title: ', call['Title'])
print('Word Count: ', len(call['Text'].split()))
print('Text:')
call['Text']This call took place on May 25th, 2016. It’s the annual shareholder meeting, and the transcript is over 20,000 words. It would be a pain to read all of it, so we’ll use python to extract insights. Currently, the contents of call["Text"] is a “string”– a sequence of characters. We can do a number of things with strings, including splitting a big string into smaller strings using a specific delimiter and the .split() function. For example, I can break down the whole text of the earnings call roughly into sentences by splitting the string every time I encounter a period (“.”). This returns a list of smaller strings, and if i select the first one using [0], I get the first sentence of this call:
call['Text'].split('.')[0]"I'm Rex Tillerson, I'm the Chairman and Chief Executive Officer of the Exxon Mobil Corporation"
Lovely! the first sentence is an introduction by then-CEO Rex Tillerson.
![]()
He was CEO of Exxon from 2006 until he retired on January 1st 2017. One month later, he was sworn in as U.S. Secretary of State under Donald Trump. Let’s see what Rex thinks about climate change!
Counting words
Strings can also be searched. .lower() makes all the text lower case (so “Climate Change” and “climate change” are treated the same), and .count() counts how many times a phrase appears. How many times is “climate change” mentioned in this call?
# make the text lower case, then count the mentions of "climate change"
call['Text'].lower().count('climate change')Looks like climate change is mentioned 51 times in this earnings call.
Exercise
how many times is the phrase “global warming” mentioned?
But we have 182 earnings calls in this sample– suppose we want to count the number of times climate change is mentioned in each one, so we can see the salience of this topic over time.
Applying a lambda function to a dataframe
Because each row of our dataframe df is an earnings call (the text of which is contained in df['Text'], we want to apply the analysis we did for the single earnings call above to each row of df.
We can accomplish this using a lambda function. This allows us to iterate over each value in a dataframe column, and apply a function to it. In the simple example below, I use a lambda function to create a new column that is takes the values from a different column and multiplies them by 2:
# create a dataframe called "example" with one column called "numbers" which contains numbers 0-5
example= pd.DataFrame({'numbers':[0,1,2,3,4,5]})
# print the dataframe
print("\n Before applying lambda function: \n", example)
# create a new column called "doubled numbers"
# apply a lambda function that iterates over each row in the "numbers" column
# call each row "x", and multiply it by 2
example['doubled numbers']= example['numbers'].apply(lambda x: x*2)
# print the dataframe, which now contains the new column
print("\n \n After applying lambda function: \n", example)
Before applying lambda function:
numbers
0 0
1 1
2 2
3 3
4 4
5 5
After applying lambda function:
numbers doubled numbers
0 0 0
1 1 2
2 2 4
3 3 6
4 4 8
5 5 10
There were simpler ways of doing this (namely, example[doubled numbers]=example['numbers']*2). But if we want to do something more complex, lambda functions are very useful. Remember, we used call['Text'].lower().count('climate change') to count the mentions of climate change in one earnings call. We can turn this into a lambda function as follows:
df['Text'].apply(lambda x: x.lower().count('climate change'))
df['Text']: the column we want to iterate over..apply(lambda x:: iterate over each row in the column, and call each value in that column x. In other words, x will represent the text of each earnings call.x.lower().count('climate change'): this is exactly the same as what did previously to find the number of mentions of climate change in the one earnings call, except that we swappedcall['Text']withx, since we want to do this for the text of every earnings call.
# create a column called "climate change" that contains the count of mentions of this keyword
df['climate change']=df['Text'].apply(lambda x: x.lower().count('climate change'))
# print the title of each earnings call, along with the number of mentions of climate change.
print(df[['Title','climate change']])Amazing! We’ve now got a column indicating how many times “climate change” was mentioned in each earnings call.
Exercise
Create three new columns that count the frequency of the terms “global warming”, “carbon capture”, and another phrase or word of your choosing. When you’ve done this, edit the code below so that it not only shows the frequency of “climate change” mentions, but also the three additional columns you created.
Advanced: Our current measure of the number of mentions of keywords might be biased: if one earnings call mentions climate change 10 times more than another, but that earnings call has 10 times more words, then the rate of keyword mentions hasn’t actually increased; people are just talking more. You can get the word count of each earnings call in the lambda function above using len(x.split()) (careful: len(x) on its own counts characters, not words). Edit the lambda function above such that we don’t get a count of the number of mentions of climate change, but the rate of mentions (i.e., count of “climate change” divided by total word count per call).
Let’s plot the frequency of these mentions over time to analyze temporal trends in the salience of climate change and other keywords in these calls. We’ll accomplish this using
# extract the year from the date column
df['Year']=df['Date'].dt.year
# group the dataframe by year, calculating the sum of the "climate change" column
# save it as a new dataframe called "yearly"
yearly=df.groupby('Year')['climate change'].sum()
# plot yearly
yearly.plot()<matplotlib.axes._subplots.AxesSubplot at 0x7f7d77456890>

Careful: some years have many more calls (and many more words) than others, so a yearly total can rise just because people talked more. Dividing by the number of words gives a rate: mentions per 10,000 words.
# count the words in each call
df['words']=df['Text'].apply(lambda x: len(x.split()))
# add up mentions and words for each year, then divide to get a rate
yearly=df.groupby('Year')[['climate change','words']].sum()
yearly['rate']=yearly['climate change']/yearly['words']*10000
# plot the rate
yearly['rate'].plot()Do you notice any patterns in the salience of these topics over time?
Finding sentences
We can see how often climate change comes up, but what are people actually saying about it? Let’s pull out every sentence that mentions it. A rough way to split text into sentences is to cut it wherever there is a full stop followed by a space ('. '):
# join all the transcripts into one long string, and split it into sentences
sentences = " ".join(df['Text']).split('. ')
# keep only the sentences that mention climate change
climate_sentences = [s for s in sentences if 'climate change' in s.lower()]
print(len(climate_sentences))
# print the first 10 sentences in the list
for sentence in climate_sentences[:10]:
print('\n', sentence)Semantic Analysis
Now we can see the sentences which mention climate change, which helps us understand a bit about the context. We can perform semantic analysis on some of these sentences to take a close look at the grammar of some of these sentences; I’ve picked one of them and produced a dependency tree, like the ones we’ve seen in class.
from spacy import displacy
#run the NLP pipeline on one of our sentences about climate change.
doc = nlp(climate_sentences[87].strip())
#print out the dependency tree
displacy.render(doc, jupyter=True)The root of this dependency tree is the verb “presents”. The subject is Exxon, and the object is “a false choice”. But we’re still missing one vital piece of information: who is speaking? It makes a big difference to our understanding of whats going on. Are mentions of climate change increasing over time because shareholders are asking more questions? Or did CEO Rex Tillerson have a spiritual awakening in which all he wants to do is talk about climate change? For that, we need to figure out who’s talking, and resturcture our dataframe.
Who is speaking?
In the transcripts, every new speaker is introduced in capital letters followed by a colon, like this:
PHILIP WEISS, ANALYST, ARGUS RESEARCH COMPANY: Good morning. I did have one...
DAVID ROSENTHAL: Sure. The fall off in the liquids is...
To find these labels we need a search pattern rather than a fixed phrase. Python’s re library does this with regular expressions. You don’t need to learn them for this course; just know that the pattern [A-Z]+.+[A-Z]+: means “capital letters, then anything, then capital letters and a colon”. re.findall() returns every match, giving us a list of the speakers on this call:
# create a list of all the speakers by searching text of the earnings call for the pattern above.
speakers = re.findall(r'([A-Z]+.+[A-Z]+: )', call['Text'])
# because they don't introduce the speaker in the opening statement, insert a placeholder at the beginning of this list.
speakers.insert(0,'INTRODUCTION')
# using set(list) will give you the unique values in a list
# the length of set(list) gives us the number of unique speakers
print('There are', len(set(speakers)),'speakers on this call:')
# let's print out the first 10 speakers:
for speaker in speakers[:10]:
print(speaker)There are 31 speakers on this call:
INTRODUCTION
JEFF WOODBURY, VP OF INVESTOR RELATIONS, CORPORATE SECRETARY, EXXONMOBIL CORPORATION:
REX TILLERSON:
REX TILLERSON:
REX TILLERSON:
BETH RICHTMAN, INVESTMENT MANAGER, CALPERS:
REX TILLERSON:
MICHAEL CROSBY, CAPUCHIN FRANCISCAN FRIAR:
REX TILLERSON:
TRACEY REMBERT, SHAREHOLDER, CHRISTIAN BROTHERS INVESTMENT SERVICES:
We want to do more than just identify the speakers though; we want to break up the text of our earnings call into chunks of speech and associate each chunk of speech with its speaker. re.split() cuts the text at every match of the same pattern, and returns a list of the chunks in between:
# split the text of the earnings call at the same pattern, save the list as "speech"
speech=re.split(r'[A-Z]+.+[A-Z]+: ', call['Text'])
# now, we can print the fourth speaker:
print('Speaker: \n', speakers[3])
# and the text of the fourth speech:
print('\n Speech: \n', speech[3])Speaker:
REX TILLERSON:
Speech:
So now, turning to the formal business of the meeting and a few brief remarks on shareholder proposals and voting. Each year, the corporation receives a number of suggestions from shareholders. Some of these are in the form of proposals to be presented at the Annual Meeting and each is given careful consideration.
We seek dialogues with the sponsors prior to the meeting when there is more time to better understand each other's positions and we often find agreement. Let me be clear on the conduct of the meeting. Recognizing that the majority of our shareholders have voted by proxy and are not present, we have established procedures to facilitate an orderly meeting.
We've set up a process for speakers to identify themselves and to express their views and I assure you, we welcome those views. In order that as many shareholders as possible can participate, we have set time limits and a system of reminders to help you manage your time.
We have 14 items to consider. As Secretary Woodberry said earlier, discussion on all items of business will be deferred to the discussion period. This may enable us to have some time for general comments and questions as well and conclude the meeting in a reasonable time frame.
For those of you who may wish to leave the meeting at any time, let me express my appreciation for your attendance. Since we have a number of items yet to discuss on the program and you've been sitting for a while, I would invite you to stand and take a short stretch break and I would ask that you not leave the hall. We'll resume in just a moment.
(Break)
Now we’ve associated chunk of speech with their speaker, amazing. Let’s create a new dataframe that reflects this structure. Currently, our dataframe call has one row. Let’s use the two lists we just created, speakers and speech, to create a dataframe in which each row is one chunk of speech. A column called “speaker” will indicate who is speaking, and a column called “speech” will contain the text of the speech:
# create the new dataframe, from the two lists, and name it "speaker_df"
speaker_df=pd.DataFrame({"speaker":speakers,"speech":speech})
# clean up the "speaker" column by removing the colons using .str.replace(":","")
# remove trailing white space using str.rstrip()
speaker_df['speaker']=speaker_df['speaker'].str.replace(':','').str.rstrip()
# print rows in which rex tillerson is speaking:
print(speaker_df[speaker_df['speaker']=="REX TILLERSON"]) speaker speech
2 REX TILLERSON Thank you, Jeff. We will address our items of ...
3 REX TILLERSON So now, turning to the formal business of the ...
4 REX TILLERSON If you'd please take your seats. The first ite...
6 REX TILLERSON Thank you. The Board recommends a vote against...
8 REX TILLERSON Thank you, Fr. Crosby. The Board recommends a ...
10 REX TILLERSON Thank you, Ms. Rembert. The Board recommends a...
12 REX TILLERSON Thank you, Mr. Garland. The Board recommends a...
14 REX TILLERSON Thank you, Mr. Sifferman. The Board recommends...
16 REX TILLERSON Thank you, Mr. Jenkins. The Board recommends a...
18 REX TILLERSON Thank you, Ms. Lamb. The board recommends a vo...
20 REX TILLERSON I'm well. Thank you.\n\n
22 REX TILLERSON Thanks, Sister Pat. The board recommends a vot...
24 REX TILLERSON Thank you, Mr. Mason. The board recommends a v...
26 REX TILLERSON Thank you, Ms. Fugere. The board recommends a ...
28 REX TILLERSON Thank you, Ms. Fugere. The board recommends a ...
29 REX TILLERSON Okay, let's resume the meeting, so if you woul...
30 REX TILLERSON There in the back.\n\n
32 REX TILLERSON Thank you. Other speakers? All right, down her...
34 REX TILLERSON Well, ALEC, as you probably know, is an organi...
36 REX TILLERSON Well, as you and I have spoken before, my view...
38 REX TILLERSON I understand, and so I'm going to respond to a...
40 REX TILLERSON Thank you. In the inside aisle here.\n\n
42 REX TILLERSON Speculating on future court events would be ir...
44 REX TILLERSON The only way I know to respond is to tell you ...
46 REX TILLERSON And we have responded to those allegations as ...
48 REX TILLERSON Could you begin to wrap it up?\n\n
50 REX TILLERSON Thank you. So over here to this side of the ha...
52 REX TILLERSON Well, as to Saudi Aramco's views or the Kingdo...
54 REX TILLERSON I wish my dad had bought some shares the year ...
56 REX TILLERSON Thank you for those kind words. Right here.\n\n
58 REX TILLERSON We will continue to engage in the policy discu...
59 REX TILLERSON I believe all the items of business have been ...
60 REX TILLERSON While the inspectors of election are preparing...
62 REX TILLERSON Well, I'm not sure I would characterize it as ...
64 REX TILLERSON Well, as many of have heard me say before, if ...
65 REX TILLERSON The inspectors of election are ready to report...
67 REX TILLERSON Thank you. As stated in the written report of ...
Active and passive voice
And there we have it. We started with a PDF on a website, and we’ve ended up with a dataframe in which each row is a speech, with a column indicating who is speaking and what they’re saying. Now let’s use it to look at how things are said.
Who did it? The passive voice
In the lecture we saw that “the officer shot the man” and “an officer-involved shooting occurred” describe the same event, but only one of them says who did it. The dependency parse lets us spot this automatically:
nsubj: the subject of an active verb (the do-er)nsubjpass: the subject of a passive verb (“the man was shot”)agent: the “by …” phrase that names who did it in a passive sentence
# two sentences about the same event
for sentence in ["Exxon spilled oil into the river.", "Oil was spilled into the river."]:
doc = nlp(sentence)
print(sentence)
# print each word and its grammatical role
for token in doc:
print(' ', token.text, token.dep_)# a function that returns True if a sentence is in the passive voice
def is_passive(sentence):
doc = nlp(sentence)
return any(token.dep_ == 'nsubjpass' for token in doc)
# check the first 200 sentences about climate change
passive_sentences = [s for s in climate_sentences[:200] if is_passive(s)]
print(len(passive_sentences), 'of 200 climate change sentences are passive')
passive_sentences[:5]Exercise
- Write two headlines about the same event, one active and one passive (e.g. “Tanker hits pier” / “Pier was hit”). Run them through the cell above. Does spaCy get the voice right?
- Read some of the passive climate sentences. Is anyone hiding who did what, or is the passive natural there?
Who uses the passive voice?
Now that we know who is speaking, we can ask: does Rex Tillerson use the passive voice more than the shareholders questioning him? We split each speech into rough sentences at full stops, check each one, and compare the share of passive sentences:
# label each speech as Tillerson's or someone else's
speaker_df['group'] = 'Others'
speaker_df.loc[speaker_df['speaker'] == 'REX TILLERSON', 'group'] = 'Rex Tillerson'
# split every speech into sentences, and check whether each one is passive
rows = []
for group, speech in zip(speaker_df['group'], speaker_df['speech']):
for sentence in speech.split('. '):
rows.append({'group': group, 'passive': is_passive(sentence)})
sentence_df = pd.DataFrame(rows)
# the mean of True/False values is the share that are True
sentence_df.groupby('group')['passive'].mean()Exercise
Who uses the passive voice more? Print some of Tillerson’s passive sentences: what is he avoiding saying, if anything?
External pressure
The fact that Exxon knew about climate change in the 1970s and still funded climate denial resulted in public outrage, culminating in an online movement organized around the twitter hashtag #ExxonKnew.
I’ve downloaded almost 100,000 tweets containing the hashtag #ExxonKnew, between 2016 and 2017. Work together as a group to explore and analyze this dataset.
tweets=pd.read_csv('https://storage.googleapis.com/qm2/wk4/Exxon_tweets_clean.csv')
tweetsSentiment Analysis
Sentiment analysis is the computational study of people’s opinions, sentiments, emotions, appraisals, and attitudes towards entities such as products, services, organizations, individuals, issues, events, topics, and their attributes. Let’s study the sentiment of the tweets in this dataset.
spacytextblob performs sentiment analysis using the TextBlob library. Adding spacytextblob to a spaCy nlp pipeline creates a new extension attribute for the Doc.
The ._.blob attribute contains all of the methods and attributes that belong to the textblob.TextBlob class. Some of the common methods and attributes include:
._.blob.polarity: a float within the range [-1.0, 1.0].._.blob.subjectivity: a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.._.blob.sentiment_assessments.assessments: a list of polarity and subjectivity scores for the assessed tokens.
Let’s run sentiment analysis on a single tweet:
# grab the 130th row in the dataframe and select the text of the tweet
text=tweets.iloc[130]['text']
# apply the NLP pipeline to this text.
doc = nlp(text)
print(text)
print('Polarity: ', doc._.blob.polarity)
print('Subjectivity: ', doc._.blob.subjectivity)
print('Assessments: ', doc._.blob.sentiment_assessments.assessments)RT @Exxon_Knew: Stop saying #Tillerson is good on climate. He leads the oil company WORST on climate #ExxonKnew via @jacobwe https://t.co/P…
Polarity: -0.15000000000000002
Subjectivity: 0.8
Assessments: [(['good'], 0.7, 0.6000000000000001, None), (['worst'], -1.0, 1.0, None)]
We can see that the model has deemed this tweet to be expressing negative sentiment: it has a polarity of -0.15. It also deems this to be a pretty subjective tweet, with a subjectivity score of 0.8. It does indeed appear to be expressing a subjective opinion. Finally, we can see which words are leading to this assessment. The word “good” is leading to a 0.7 increase in the polarity score, and a 0.6 increase in the subjectivity score. The word “worst” is leading to a -1 change polarity, and a +1 change in subjectivity. The overall scores are weighted averages of these values. Though these scores do roughly align with the actual sentiment of this tweet, ALWAYS pay attention to whats going on inside of your sentiment analysis pipeline. Even though the overall sentiment score here is negative, it should probably be even more negative; the algorithm picked up on the word “good” in this tweet, and this improved the polarity score by 0.7. But the context in which “good” was uttered in this tweet is actually negative! the person is saying “stop saying #Tillerson is good on climate”– this is expressing negative sentiment!
Assessed Question
The URL below contains the speaker turns from Exxon’s annual shareholder meetings, 2004-2019: one row per speaker turn, like the speaker_df dataframe we built above, but for all the meetings. The columns are date, year, title, name, affiliation, speaker (Exxon for company executives, Investor for shareholders), words (number of words in the turn) and text.
https://oballinger.github.io/BASC0005/data/assessed/w04_exxon_agm_turns.csv
Note that the file may have been corrupted; some values or labels may be wrong, so make sure to sense-check your data before answering.
QUESTION: Measure shareholder pressure on fracking: for each year, count mentions of “fracking” and “hydraulic fracturing” (case-insensitive) in investor turns, divided by the number of words investors spoke that year (mentions per 1,000 words). In which year was shareholder pressure on fracking highest?
Keep a note of your answer: you will enter it in the Problem Set Answers quiz on Moodle in December.
# your code here(Optional) Extension: tense
spaCy also records the tense of each verb in token.morph. Is Exxon talking about climate change in the past (“we have invested”) or the future (“we will reduce”)? The cell below counts past- and present-tense verbs in the first 200 climate change sentences.
# count the tense of every verb in the first 200 climate change sentences
tenses = []
for doc in nlp.pipe(climate_sentences[:200]):
for token in doc:
tenses += token.morph.get('Tense') # e.g. ['Past'], or [] for words that aren't verbs
pd.Series(tenses).value_counts()English has no future tense ending, so “will reduce” shows up as the word “will” plus a verb with no tense. Try counting how often “will” appears in the climate sentences, and compare with the sentences about earnings or dividends. Is Exxon more forward-looking about climate than about money?
# your code here